package as3.component
{
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import as3.component.iface.IFadeInOutSprite;
	
	import gs.TweenMax;

	public class FadeInOutSprite extends Sprite implements IFadeInOutSprite
	{
		private var _timer:Timer;
		private var _duration:uint;//显示的时间
		private var _autoDdisappear:Boolean = true; //是否自动消失，默认为true
		private var _tweenMax:TweenMax;
		protected static const DEFAULT_DURATION:uint = 1000;
		protected static const TWEEN_DURATION:Number = .4
		public function FadeInOutSprite()
		{
			super();
			_duration = DEFAULT_DURATION;
			configureEventListener()
		}
		
		private function configureEventListener():void
		{
			addEventListener(Event.REMOVED_FROM_STAGE,removedHandler);
			addEventListener(Event.ADDED_TO_STAGE,addToStageHandler);
		}
		
		protected function addToStageHandler(e:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE,addToStageHandler);
			if(!_timer)
			{
				_timer = new Timer(_duration,1)
				_timer.addEventListener(TimerEvent.TIMER,hideHandler);
			}
			if(!parent)
				return;
			if(_autoDdisappear)
			{
				_timer.reset();
				_timer.start();
			}
			_tweenMax = TweenMax.from(this,TWEEN_DURATION,{y: y+10,alpha:0});
		}
		
		private function hideHandler(e:TimerEvent = null):void
		{
			_tweenMax = TweenMax.to(this, TWEEN_DURATION, {y: y - 20, alpha:0,onComplete:onTweenComplete});
		}
		
		public function show(parent:DisplayObjectContainer):IFadeInOutSprite
		{
			parent.addChild(this);
			return this;
		}
		
		public function hide():void
		{
			hideHandler();
		}
		
		private function onTweenComplete():void
		{
			_tweenMax = null;
			parent.removeChild(this);
		}
		
		protected function removedHandler(e:Event):void
		{
			if(_timer)
				_timer.removeEventListener(TimerEvent.TIMER,hideHandler);
			_timer = null;
				
			removeEventListener(Event.REMOVED_FROM_STAGE,removedHandler);
		}
		
		public function set appareDuration(value:uint):void
		{
			_duration = value;
		}
		
		public function set autoDisappear(value:Boolean):void
		{
			_autoDdisappear = value;
		}
		
	}
}